#!/usr/bin/env python
# coding: utf-8

# Setp one:
# note: Reload django settings
import logging
import json
import os
import sys
import time

import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
os.chdir(os.path.join(BASE_DIR, "yijiao_main"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
sys.path.insert(0, os.path.join(BASE_DIR, "pylib"))
sys.path.insert(0, os.path.join(BASE_DIR, "yijiao_main"))
django.setup()

# Setp two:
# note: Load function with logging, django model
from services.datamodel.question.models import BlankFillQuestion, UniversalQuestion, QUniversalTags

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    filename=os.path.join("/tmp", "migrate_universal_question.log")
)


# Setp three:
# note: Running
def migrate_universal_question():
    qtagsubjectid_to_qtaginstance = {}
    for qtag in QUniversalTags.objects.filter(name="填空题"):
        qtagsubjectid_to_qtaginstance[qtag.subjectid] = qtag

    for qs in list(BlankFillQuestion.objects.all().values()):
        try:
            qs["qtag"] = qtagsubjectid_to_qtaginstance[qs["subjectid"]]
        except KeyError:
            logging.error("no subjectid is _%s_, blankfill's id is _%s_" % (qs["subjectid"], qs["id"]))
            continue
        qs["answer"] = json.dumps([{
            "qtype": 2,
            "num": qs["blankcount"],
            "subcontent": {
                "correct": json.loads(qs["answer"]),
                "title": "",
                "opts": [],
            }
        }])
        del qs["blankcount"]
        UniversalQuestion(**qs).save()
        logging.info("successed operation with _%s_ of blankfill's id" % qs["id"])
    logging.info("end")


if __name__ == "__main__":
    start_time = time.time()
    migrate_universal_question()
    print(time.time() - start_time)
